package group9;


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.*;

import com.google.appengine.api.datastore.Key;

/**
 * @author Claudio Herreros, Dylan James, Tyler Berg
 *
 */

@SuppressWarnings("serial")
public class EditEstimatorServlet extends HttpServlet {
	public void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {

		String delimiters = ",";
		String username = req.getParameter("usernames");
		String[] usernames = username.split(delimiters);
		
		System.out.println(username);
		

		PersistenceManager pm = PMF.get().getPersistenceManager();
		User user = (User) req.getSession().getAttribute("User");
		user = (User) pm.getObjectById(User.class, user.getKey());

		
		if (user == null)
		{
			resp.sendRedirect("index.html");
			return;
		}
		
		
		List<Key> keys = new ArrayList<Key>();
		
		UserStory us = (UserStory) req.getSession().getAttribute("UserStory");
		us = (UserStory) pm.getObjectById(UserStory.class, us.getKey());
		
		System.out.println("here4  "+ usernames.length + "   :" + username + ": ");
		
		for(int i = 0; i < usernames.length; i++){
			System.out.println("here1");
			Query userQuery = pm.newQuery("select from " + User.class.getName() + " where userName == '" + usernames[i] + "'");
			System.out.println("here2");
			List<User> results = (List<User>) userQuery.execute();
			System.out.println("here3");
			if (results.isEmpty()){
				System.out.println("Empty");
				//throw error
				//resp.sendRedirect("claim estimators page");
				//return;
			}else{
				System.out.println(results.get(0).getUserName());
				keys.add(results.get(0).getKey());
				System.out.println("here5");
				if(us.getKey() != null){
					System.out.println(us);
				}else{
					System.out.println("NULL");
				}
				//results.get(0).addEstUserStory(us.);
				System.out.println("here6");
			}
			System.out.println("here7");
		}
		System.out.println("here Final");
		
		
		List<Estimate> estimates = us.getEstimates();
		
		//ArrayList<Estimate> newEstimates = new ArrayList<Estimate>();
		
		boolean exists = false;
		System.out.println("here6");
		
		for(int i = 0; i < keys.size(); i++){
			us.addEstimator((User) pm.getObjectById(User.class, keys.get(i)));
		}
		System.out.println("here7");
		System.out.println(us.existsEstimator(user));
		//us.setEstimates(newEstimates);
		try{
			//pm = PMF.get().getPersistenceManager();
			pm.makePersistent(us);
			pm.flush();
		}finally{
			pm.close();
		}
		
		req.getSession().setAttribute("UserStory", us);
		System.out.println(us.existsEstimator(user));
		//redirect
		resp.sendRedirect("/MyUserStories.jsp");
	}
}